package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.constant.RedisConstant;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.BeanConv;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.SetMealMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckGroupService;
import com.itheima.utils.AliyunUtils;
import com.itheima.service.SetmealService;
import com.itheima.vo.CheckGroupVo;
import com.itheima.vo.SetmealVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author ：yuanjian
 * @date ：Created in 2020/11/11 14:54
 * @description：
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetmealService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CheckGroupService checkGroupService;


    @Override
    @Transactional
    public void save(SetmealDto setmealDto) {
        Setmeal setmeal = BeanConv.toBean(setmealDto, Setmeal.class);
        //如果执行添加则groupId为null，执行修改则groupId不为null
        Long setmealId = setmeal.getId();
        List<Long> checkgroupIds = setmealDto.getCheckgroupIds();
        //执行修改操作1.删除联系表中相关数据
        if (setmeal.getId() != null) {
            baseMapper.deleteCheckGroupBySetmealId(setmealId);
        }

        //执行添加操作1.添加group信息  或  执行更新操作2.修改group信息
        saveOrUpdate(setmeal);

        //删除redis中set集合中的图片
        redisTemplate.opsForSet().remove(RedisConstant.ALL_SETMEAL_PIC_SET,setmealDto.getImg());
        //删除redis中的key
        redisTemplate.delete(RedisConstant.SINGLE_PIC+setmealDto.getImg());

        //添加和修改操作的最后一步都是：添加相关联系表的数据
        if (checkgroupIds != null && checkgroupIds.size() != 0) {
            for (Long checkgroupId : checkgroupIds) {
                baseMapper.addSetmealAndCheckGroupIds(setmeal.getId(), checkgroupId);
            }
        }
        //每次新增或修改完，都更新移动端redis的数据
        // 如果是修改操作，则直接向redis里修改数据
        if (setmealId!=null){
            redisTemplate.opsForHash().put("com:itheima:pojo:setmeal","id-"+setmealId,getById(setmealId));
            findSetMealDetail(setmealId);
        }else {//否则重新查询所有数据，再添加到redis中
            findSetmealAll();
        }
    }

    @Override
    public PageResult findByPage(QueryPageBean pageBean) {
        IPage<Setmeal> page = new Page<>();
        //如果查询条件不为空或trim后不为null，执行条件查询
        if (!(StringUtils.isEmpty(pageBean.getQueryString()) && StringUtils.trimAllWhitespace(pageBean.getQueryString()) == null)) {
            //分页查询is_delete=0的数据，且 查询条件是name或code或helpcode三者的模糊查询
            page = page(new Page<>(pageBean.getCurrentPage(), pageBean.getPageSize()), new QueryWrapper<Setmeal>().eq("delete_flag", 0)
                    .and(wrapper -> {
                        wrapper.like("name", pageBean.getQueryString()).or()
                                .like("code", pageBean.getQueryString()).or()
                                .like("help_code", pageBean.getQueryString());
                    })
            );

        } else {
            page = page(new Page<>(pageBean.getCurrentPage(), pageBean.getPageSize()), new QueryWrapper<Setmeal>().eq("delete_flag", 0));

        }
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public List<Long> findCheckItemByCheckGroupId(Long setmealId) {
        return baseMapper.findCheckGroupBySetmealId(setmealId);
    }

    //  清理  oss  垃圾图片   该方法 有  xxl-job 去调用
    @Override
    public void clearOssImg() {
        //  1.  获取 set 集合 所有图片信息
        Set<Object> objects = redisTemplate.opsForSet().members(RedisConstant.ALL_SETMEAL_PIC_SET);
        if (objects.size() != 0) {
            for (Object uuidfilename : objects) {
                //   遍历 图片  判断 redis 该图片有没有存在
                Boolean hasKey = redisTemplate.hasKey(RedisConstant.SINGLE_PIC + uuidfilename);
                //不存在，说明图片已经存到数据库中 或者 图片已经过了超时时间，
                // 需要删除阿里云上的该图片,而且删除redis的set集合中的value值.
                if (!hasKey) {
                    AliyunUtils.deleteFile(uuidfilename.toString());
                    System.out.println("-----阿里云删除垃圾图片一次----");
                    redisTemplate.opsForSet().remove(RedisConstant.ALL_SETMEAL_PIC_SET, uuidfilename);
                }
            }
        }
    }

    @Override
    public boolean deleteById(Long id) {
        Setmeal setmeal = baseMapper.selectById(id);
        if (setmeal != null){
            setmeal.setDelete_flag(1);
        }
        //将redis里的setmeals删除，并删除此套餐详情
        if (redisTemplate.opsForHash().get("com:itheima:pojo:setmeal","id-"+id)!=null);{
            redisTemplate.opsForHash().delete("com:itheima:pojo:setmeal","id-"+id);
            redisTemplate.delete("com:itheima:pojo:setmealVo"+id);
        }
        return updateById(setmeal);
    }

    @Override
    public SetmealVo findSetMealDetail(Long setmeaId) {
        //1.查询setmeal
        Setmeal setmeal = getById(setmeaId);
        SetmealVo setmealVo= new SetmealVo();
        BeanUtils.copyProperties(setmeal,setmealVo);
        List<CheckGroupVo> checkGroupVos = baseMapper.findCheckGroupsBySetmealId(setmeaId);
        if (checkGroupVos != null) {
            for (CheckGroupVo checkGroupVo : checkGroupVos) {
                List<CheckItem> checkItems = checkGroupService.findCheckItemsByCheckGroupId(checkGroupVo.getId());
                checkGroupVo.setCheckItems(checkItems);
            }
        }
        setmealVo.setCheckGroupVos(checkGroupVos);
        redisTemplate.opsForValue().set("com:itheima:pojo:setmealVo"+setmeaId,setmealVo);
        System.out.println("使用mysql查询setmealVo");
        return setmealVo;
    }

    @Override
    public List<Setmeal> findSetmealAll() {

        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag",0);
        List<Setmeal> setmealList = list(queryWrapper);
        for (Setmeal setmeal : setmealList) {
            redisTemplate.opsForHash().put("com:itheima:pojo:setmeal","id-"+setmeal.getId(),setmeal);
        }
        System.out.println("使用mysql查询setmealList");
        return list();
    }
}
